#include <iostream>
#include <sstream>
#include <string>
#include <vector>
// g++ -o test test.cc
#include "json.hpp"
using namespace std;
using namespace nlohmann;
enum Hobby {
  STUDY = 0,
  SLEEP = 1,
  WORK = 2,
};

void Test1(json& j) {
  // 赋值json对象方式一：
  j["name"] = "lei";
  j["age"] = 22;
  j["height"] = 170;
  j["weight"] = 60;
  j["hobby"] = Hobby::STUDY;
  j["friends"] = {"du", "you", "ren", "yang", "xiong"};

  j["job"]["job_name"] = "it";
  j["job"]["salary"] = 400000;
  // j["job"] = {{"job_name","it"},{"salary",400000}};

  // 方式二，与上等价
  //   json j = {{"name", "lei"},
  //             {"age", 22},
  //             {"height", 170},
  //             {"hobby", Hobby::STUDY},
  //             {"friends", {"du", "you", "ren", "yang", "xiong"}},
  //             {"job", {{"job_name", "it"}, {"salary", 400000}}}};

  // 序列化：获取存储在内存中的字符串
  string str = j.dump();
  // 使用流进行序列化
  //   ostringstream oss;
  //   oss << j;
  //   string str = oss.str();
  //   cout << "str.size()=" << str.size() << endl;
  //   cout << "str:" << str << endl;

  json j2 = json::parse(str);  // 反序列化，使用json::parse函数
  cout << j2["name"] << endl;
  cout << j2["age"] << endl;
  cout << j2["height"] << endl;
  cout << j2["weight"] << endl;
  cout << j2["hobby"] << endl;
  vector<string> tmp = j2["friends"];
  for (auto& t : tmp) {
    cout << t << " ";
  }
  cout << endl;
  cout << j2["job"]["job_name"] << endl;
  cout << j2["job"]["salary"] << endl;
  string j2_job_job_name = j2["job"]["job_name"];
  cout << "j2_job_job_name.size()=" << j2_job_job_name.size()
       << ",j2_job_job_name:" << j2_job_job_name << "#" << endl;  // #号为结束符
  cout << "----------Test1 Finished!-----------" << endl;
}

void Test2(json& j1) {
  json j2;
  // 反序列化，使用流
  istringstream iss;
  string s = j1.dump();
  cout << s << endl;
  iss.str(s);
  iss >> j2;

  cout << j2["name"] << endl;
  cout << j2["age"] << endl;
  cout << j2["height"] << endl;
  cout << j2["weight"] << endl;
  cout << j2["hobby"] << endl;
  vector<string> tmp = j2["friends"];
  for (auto& t : tmp) {
    cout << t << " ";
  }
  cout << endl;
  cout << j2["job"]["job_name"] << endl;
  cout << j2["job"]["salary"] << endl;
  string j2_job_job_name = j2["job"]["job_name"];
  cout << "j2_job_job_name.size()=" << j2_job_job_name.size()
       << ",j2_job_job_name:" << j2_job_job_name << "#" << endl;  // #号为结束符
  cout << "----------Test2 Finished!-----------" << endl;
}
int main() {
  json j;
  Test1(j);
  Test2(j);
  return 0;
}